#!/bin/bash
version="V1.1"
echo "The script version is $version."

if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root!" 1>&2
   exit 1
fi

if ! [ -x "$(command -v wget)" ]; then
	if [[ -f  /home/avc/wget_1.17.1-1ubuntu1.5_armhf.deb ]]; then
		dpkg -i wget_1.17.1-1ubuntu1.5_armhf.deb &&
		rm wget_1.17.1-1ubuntu1.5_armhf.deb
	else
		echo 'Error: wget is not installed.' >&2
		exit 1
	fi
fi

fpga_path="/sys/kernel/debug/iio/iio:device3/direct_reg_access"
if [ ! -f $fpga_path ];then
	echo "Count not find dev!"
	exit 1
fi

echo 0x80000114 > $fpga_path
mode=$(cat $fpga_path) 
let "mode&=0x00d00000"

if [ $mode -eq 0 ];then 
        mode="CMOS"
else
        mode="LVDS"
fi
echo "Current mode is $mode"
echo 0x80000110 > $fpga_path 
cur_ver=$(cat $fpga_path)
cur_ver=${cur_ver#*"x"}

if [[ ! -n $cur_ver ]];then
	echo "Count not get current version!"
	exit 1
fi

board=$(cat /proc/device-tree/model) >&2
if [[ $board =~ "ZED" ]]; then
        board="ZedBoard"
        echo "Current board is ZedBoard"
elif [[ $board =~ "ZC706" ]]; then
        board="ZC706"
        echo "Current board is ZC706"
else
        echo "Device tree don't have describe as ZedBoard or ZC706"
        exit 1
fi

wget -q "http://192.168.50.4:8001/boot/$board/$mode/" -O .boot_info.txt
while read line
do
	if [[ $line =~ "href=\"" ]]
	then
		ver=${line#*"\""}
		ver=${ver%%"/"*}
		ver=$((10#$ver))
		if ((ver >= tmp))
		then
			tmp=$ver
		fi
	fi
done < .boot_info.txt
rm .boot_info.txt

if (( tmp > cur_ver ));then
    echo "The current version is $cur_ver and the newest version is $tmp."
	read -p "Are you want to update to the newest version? [Y/n]" update_sel
	if [[ $update_sel = "Y" ]] || [[ $update_sel = "y" ]] || [[ $update_sel = "" ]]
	then
		echo "Update to V$tmp"
		if ! mountpoint -q /mnt; then
			mount /dev/mmcblk0p1 /mnt/
			mv /mnt/BOOT.bin /mnt/BOOT.bin.bak
			wget -c "http://192.168.50.4:8001/boot/$board/$mode/$tmp/BOOT.bin" -O /mnt/BOOT.bin
			if [ $? -ne 0 ];then
				echo "error:BOOT bin upgrade faild!"
				cp /mnt/BOOT.bin.bak /mnt/BOOT.bin
				exit 1
			fi
		fi
		echo "System will reboot right now!"
		reboot
	fi
	
	echo "Abort."	
else
	echo "Current driver is the newest!"
fi

